package com.ny.demo512;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class EmployeeFileOperation {
    public static void main(String[] args) {
        // 创建三个员工对象
        Employee employee1 = new Employee("张三", 25, 5000.0);
        Employee employee2 = new Employee("李四", 28, 6000.0);
        Employee employee3 = new Employee("王五", 30, 7000.0);

        // 将员工信息添加到文件中
        writeEmployeeToFile(employee1);
        writeEmployeeToFile(employee2);
        writeEmployeeToFile(employee3);

        // 从文件中获取员工信息并打印
        List<Employee> employees = readEmployeesFromFile();
        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }

    private static void writeEmployeeToFile(Employee employee) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("employees.txt", true))) {
            writer.write(employee.getName() + "," + employee.getAge() + "," + employee.getSalary() + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<Employee> readEmployeesFromFile() {
        List<Employee> employees = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader("employees.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                Employee employee = new Employee(parts[0], Integer.parseInt(parts[1]), Double.parseDouble(parts[2]));
                employees.add(employee);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return employees;
    }
}